import { Controller, Body, Post, Request, MessageEvent, Sse } from '@nestjs/common';
import { interval, map, Observable } from 'rxjs';

import type { ChatResult, RequestWithUser } from 'src/types';
import { AgentService } from './agent.service';
import { CreateAgentDto } from './dto/create-agent.dto';

@Controller('agent')
export class AgentController {
  constructor(private readonly agentService: AgentService) {}

  @Post('chat')
  async chat(@Body() createAgentDto: CreateAgentDto, @Request() req: RequestWithUser) {
    return this.agentService.getChatResponse(createAgentDto, req.user.id);
  }

  @Post('chat/stream')
  @Sse('chat/stream')
  chatStream(
    @Body() createAgentDto: CreateAgentDto,
    @Request() req: RequestWithUser,
  ): Observable<ChatResult> {
    const iterator = this.agentService.getChatResponseStream(createAgentDto, req.user.id);

    return new Observable<ChatResult>((observer) => {
      void (async () => {
        try {
          for await (const chunk of iterator) {
            observer.next(chunk);
          }
          observer.complete();
        } catch (err) {
          observer.error(err);
        }
      })();
    });
  }

  @Post('chat/sse')
  @Sse('chat/sse')
  sse(): Observable<MessageEvent> {
    return interval(1000).pipe(
      map(() => ({ data: { hello: 'world' + Math.random() } }) as MessageEvent),
    );
  }
}
